package pers.cj.pdos.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.Budget;
import pers.cj.pdos.entity.BusinessSet;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.entity.User;
import pers.cj.pdos.excel.ExcelBudgetIn;
import pers.cj.pdos.excel.ExcelBudgetOut;
import pers.cj.pdos.excel.ExcelProvider;
import pers.cj.pdos.service.IBudgetService;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.BudgetVo;
import pers.cj.pdos.vo.ProviderVo;
import pers.cj.pdos.vo.UserVo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Controller
@RequestMapping("/budget")
public class BudgetController extends BaseController {
    @Autowired
    IBudgetService budgetService;
    @RequiresPermissions("budget:query")
    @RequestMapping("/budget")
    public String budget(){
        return "/budget/budget";
    }

    @RequiresPermissions("budget:query")
    @RequestMapping("/budgetIn")
    public String budgetIn(){
        return "/budget/budgetIn";
    }

    @RequiresPermissions("budget:insert")
    @RequestMapping("/budgetInNew")
    public String budgetInNew(){
        return "/budget/budgetInNew";
    }

    @RequiresPermissions("budget:insert")
    @RequestMapping("/budgetInDetail")
    public String budgetInDetail(Model model, String id){
        model.addAttribute("id",id);
        return "/budget/budgetInDetail";
    }

    @RequiresPermissions("budget:query")
    @RequestMapping("/budgetOut")
    public String budgetOut(){
        return "/budget/budgetOut";
    }

    @RequiresPermissions("budget:insert")
    @RequestMapping("/budgetOutNew")
    public String budgetOutNew(){
        return "/budget/budgetOutNew";
    }

    @RequiresPermissions("budget:insert")
    @RequestMapping("/budgetOutDetail")
    public String budgetOutDetail(Model model, String id){
        model.addAttribute("id",id);
        return "/budget/budgetOutDetail";
    }

    @ResponseBody
    @RequiresPermissions("budget:query")
    @RequestMapping("/budget/getInList")
    public ResponseList getInList(int page,
                                  int limit,
                                  String close,
                                  String search,
                                  String makeTime1,
                                  String makeTime2,
                                  String date1,
                                  String date2,
                                  String makeUserId,
                                  String storeId,
                                  String budgetProjectId,
                                  String unit,
                                  String settAccountId,
                                  String userId,
                                  String remark){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();

        List<BudgetVo> list = budgetService.listVoPage(company.getId(),
                page,
                limit,
                1,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                storeId,
                budgetProjectId,
                unit,
                settAccountId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genLikeData(remark));
        long count = budgetService.count(company.getId(),
                1,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                storeId,
                budgetProjectId,
                unit,
                settAccountId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genLikeData(remark));
        return ResponseList.success(count,list);
    }

    @ResponseBody
    @RequiresPermissions("budget:query")
    @RequestMapping("/budget/getOutList")
    public ResponseList getOutList(int page,
                                   int limit,
                                   String close,
                                   String search,
                                   String makeTime1,
                                   String makeTime2,
                                   String date1,
                                   String date2,
                                   String makeUserId,
                                   String storeId,
                                   String budgetProjectId,
                                   String unit,
                                   String settAccountId,
                                   String userId,
                                   String remark){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<BudgetVo> list = budgetService.listVoPage(company.getId(),
                page,
                limit,
                2,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                storeId,
                budgetProjectId,
                unit,
                settAccountId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genLikeData(remark));
        long count = budgetService.count(company.getId(),
                2,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                storeId,
                budgetProjectId,
                unit,
                settAccountId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genLikeData(remark));
        return ResponseList.success(count,list);
    }

    @ResponseBody
    @RequiresPermissions("budget:insert")
    @RequestMapping("/budget/add")
    public ResponseEntity add(@RequestBody Budget budget){
        Company company = getCompany();
        DataUtil.processEntity(company,budget);
        budget.setClose(false);
        budget.setMakeUserId(getLoginUserId());
        budget.setMakeTime(new Date());

        if (Utils.isEmpty(budget.getNo())) {
            return ResponseEntity.fail("编号不能为空");
        }

        if (budget.getAmt()==null) {
            return ResponseEntity.fail("金额不能为空");
        }

        if (Utils.isEmpty(budget.getStoreId())) {
            return ResponseEntity.fail("门店不能为空");
        }
        if (Utils.isEmpty(budget.getSettAccountId())) {
            return ResponseEntity.fail("账户不能为空");
        }
        if (Utils.isEmpty(budget.getBudgetProjectId())) {
            return ResponseEntity.fail("项目类型不能为空");
        }
        if (Utils.isEmpty(budget.getUserId())) {
            return ResponseEntity.fail("经办人不能为空");
        }


        if (budget.getUnitType() == 1) {
            budget.setUnit(null);
        }

        if (Utils.isEmpty(budget.getUnit())){
            budget.setUnitType(1);
            budget.setUnit(null);
        }

        if (budget.getType() == null) {
            return ResponseEntity.fail("收支类型不能为空");
        }

        budgetService.insert(budget);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("budget:close")
    @RequestMapping("/budget/close")
    public ResponseEntity close(@RequestBody Budget budget){
        try {
            //检查是否已经关闭
            if (budgetService.checkClose(budget)){
                return ResponseEntity.fail("该单据已被关闭，不能重复关闭");
            }

            budgetService.close(budget);
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("作废失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("budget:insert")
    @RequestMapping("/budget/updateImage")
    public ResponseEntity updateImage(@RequestBody Budget budget){
        try {
            Budget temp = new Budget();
            temp.setId(budget.getId());
            temp.setImage(budget.getImage());
            budgetService.updateById(temp);
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("更新图片失败");
        }
    }

    /**
     * 先更具请求数据
     * @throws IOException
     */
    @ResponseBody
    @RequiresPermissions("budget:export")
    @RequestMapping("/budgetIn/export")
    public ResponseData exportIn(String close,
                                 String search,
                                 String makeTime1,
                                 String makeTime2,
                                 String date1,
                                 String date2,
                                 String makeUserId,
                                 String storeId,
                                 String budgetProjectId,
                                 String unit,
                                 String settAccountId,
                                 String userId,
                                 String remark){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();

        List<BudgetVo> list = budgetService.listVoPage(company.getId(),
                null,
                null,
                1,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                storeId,
                budgetProjectId,
                unit,
                settAccountId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genLikeData(remark));


        String fileName = "日常收入列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelBudgetIn.class);
            sheet1.setSheetName("收入信息");
            writer.write(genExcelBudgetIn(list), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("日常收入列表导出失败");
        }
    }

    private List<ExcelBudgetIn> genExcelBudgetIn(List<BudgetVo> budgetVoList) {
        BusinessSet businessSet = getBusinessSet();
        List<ExcelBudgetIn> list = new ArrayList<>();
        for (BudgetVo budgetVo : budgetVoList){
            ExcelBudgetIn excel = new ExcelBudgetIn();
            excel.setDate(DateUtils.getDate(budgetVo.getDate(), DateUtils.YYYY_MM_DD));
            excel.setNo(budgetVo.getNo());

            if (budgetVo.getUnitType() == 1) {
                excel.setUnit("");
            } else if (budgetVo.getUnitType() == 2) {
                excel.setUnit(budgetVo.getCustom().getName());
            } else if (budgetVo.getUnitType() == 3){
                excel.setUnit(budgetVo.getProvider().getName());
            }


            excel.setBudgetProject(budgetVo.getBudgetProject().getName());
            excel.setAmt(PdosUtils.getPrice(budgetVo.getAmt(),businessSet));

            excel.setStore(budgetVo.getStore().getName());
            excel.setSettAccount(budgetVo.getSettAccountVo().getName());
            excel.setUser(budgetVo.getUser().getName());
            excel.setMaker(budgetVo.getMakeUser().getName());
            excel.setMakeTime(DateUtils.getDate(budgetVo.getMakeTime(), DateUtils.YYYYMMDD_HHMMSS));
            excel.setStatus(!budgetVo.getClose() ? "" : "作废");
            excel.setRemark(budgetVo.getRemark());
            list.add(excel);
        }
        return list;
    }

    /**
     * 先更具请求数据
     * @throws IOException
     */
    @ResponseBody
    @RequiresPermissions("budget:export")
    @RequestMapping("/budgetOut/export")
    public ResponseData exportOut(String close,
                                  String search,
                                  String makeTime1,
                                  String makeTime2,
                                  String date1,
                                  String date2,
                                  String makeUserId,
                                  String storeId,
                                  String budgetProjectId,
                                  String unit,
                                  String settAccountId,
                                  String userId,
                                  String remark){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<BudgetVo> list = budgetService.listVoPage(company.getId(),
                null,
                null,
                2,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                Utils.genDate(date1),
                Utils.genDate(date2),
                makeUserId,
                storeId,
                budgetProjectId,
                unit,
                settAccountId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genLikeData(remark));

        String fileName = "日常支出列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelBudgetOut.class);
            sheet1.setSheetName("支出信息");
            writer.write(genExcelBudgetOut(list), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("日常支出列表导出失败");
        }
    }

    private List<ExcelBudgetOut> genExcelBudgetOut(List<BudgetVo> budgetVoList) {
        BusinessSet businessSet = getBusinessSet();
        List<ExcelBudgetOut> list = new ArrayList<>();
        for (BudgetVo budgetVo : budgetVoList){
            ExcelBudgetOut excel = new ExcelBudgetOut();
            excel.setDate(DateUtils.getDate(budgetVo.getDate(), DateUtils.YYYY_MM_DD));
            excel.setNo(budgetVo.getNo());

            if (budgetVo.getUnitType() == 1) {
                excel.setUnit("");
            } else if (budgetVo.getUnitType() == 2) {
                excel.setUnit(budgetVo.getCustom().getName());
            } else if (budgetVo.getUnitType() == 3){
                excel.setUnit(budgetVo.getProvider().getName());
            }


            excel.setBudgetProject(budgetVo.getBudgetProject().getName());
            excel.setAmt(PdosUtils.getPrice(budgetVo.getAmt(),businessSet));
            excel.setStore(budgetVo.getStore().getName());
            excel.setSettAccount(budgetVo.getSettAccountVo().getName());
            excel.setUser(budgetVo.getUser().getName());
            excel.setMaker(budgetVo.getMakeUser().getName());
            excel.setMakeTime(DateUtils.getDate(budgetVo.getMakeTime(), DateUtils.YYYYMMDD_HHMMSS));
            excel.setStatus(!budgetVo.getClose() ? "" : "作废");
            excel.setRemark(budgetVo.getRemark());
            list.add(excel);
        }
        return list;
    }

    @ResponseBody
    @RequestMapping("/budget/getVoById")
    public ResponseData getVoById(String id){
        BudgetVo budgetVo = budgetService.getVoById(id);
        return ResponseData.success(budgetVo);
    }


    @ResponseBody
    @RequestMapping(value = "/budget/uploadImg", method = RequestMethod.POST)
    public ResponseData uploadImg(MultipartFile imageFile) {
        return processUploadImg(imageFile, "budget");
    }
}
